<template>
  <div id="promotionPage">
    <!-- 使用麵包屑組件 -->
    <BreadcrumbComponent :breadcrumbItems="breadcrumbItems" />
    <!-- 表格篩選 -->
    <TableFilter :config="filterConfig" @search="handleSearch" />
    <!-- 工具欄 -->
    <a-space>
      <a-button type="primary" @click="handleShowCreateDrawer">
        <template #icon>
          <PlusOutlined />
        </template>
        新建
      </a-button>
    </a-space>
    <div class="data-box">
      <a-table
        :columns="columns"
        :data-source="tableData"
        :pagination="pagination"
        :loading="loading"
      >
        <!-- 表格頭部 -->
        <template #headerCell="{ column }">
          <!-- 根據表頭字段進行表頭修飾 -->
        </template>

        <!-- 表格內容 -->
        <template #bodyCell="{ column, record }">
          <!-- 根據不同的列顯示不同的內容修飾 -->
          <template v-if="column.dataIndex === 'updatedAt'">
            {{ $formatDate(record.updatedAt) }}
          </template>
          <template v-if="column.key === 'action'">
            <a-button @click="handleView(record)">查看</a-button>
            <a-button @click="handleEdit(record)">修改</a-button>
            <a-button @click="handleCopy(record)">複製</a-button>
            <a-button danger @click="handleDelete(record)">刪除</a-button>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 修改模態框 -->
    <a-modal v-model:open="showModalEdit" :footer="null">
      <template #title>
        編輯診金方案
        <a-tag color="warning"
          ><template #icon>
            <ExclamationCircleOutlined />
          </template>
          ID: {{ editFormData.id }}</a-tag
        >
      </template>
      <DynamicForm
        ref="editFormRef"
        :fieldConfig="editFieldConfig"
        @submit="handleEditSubmit"
        :formData="editFormData"
      />
    </a-modal>

    <!-- 創建抽屜 -->
    <a-drawer
      :width="720"
      :open="showCreateDrawer"
      @close="showCreateDrawer = false"
    >
      <template #title>
        創建診金方案-
        <template v-if="step === 0"> 分成配置 </template>
        <template v-if="step === 1"> 基本信息 </template>
      </template>
      <template #extra>
        <!-- 終點步為1 -->
        <a-space v-if="step === 1">
          <a-button type="primary" @click="handlePrevStep">上一步 </a-button>
          <a-button type="primary" @click="handleCreateSubmit">提交 </a-button>
        </a-space>
        <a-space v-else>
          <a-button type="primary" @click="handleNextStep">下一步 </a-button>
        </a-space>
      </template>
      <a-flex
        v-if="spinning === true"
        align="center"
        justify="center"
        style="height: 100%"
      >
        <a-spin />
      </a-flex>
      <a-form ref="formRef" :model="formState" v-else>
        <template v-if="step === 0">
          <a-card
            v-for="(item, index) in formState.items"
            :key="index"
            :title="item.name"
            size="small"
            style="margin-bottom: 8px"
          >
            <a-row :gutter="8">
              <a-col :span="3">
                <!-- 空 -->
              </a-col>
              <a-col :span="10">
                <a-form-item label="分成類型">
                  <a-radio-group
                    v-model:value="item.shareType"
                    button-style="solid"
                    class="full-width-radio"
                  >
                    <a-radio-button :value="1">固定金額</a-radio-button>
                    <a-radio-button :value="2">百分比</a-radio-button>
                  </a-radio-group>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="佣金">
                  <a-input-number
                    v-model:value="item.shareValue"
                    :precision="2"
                    :step="0.1"
                    :min="0"
                    :max="item.shareType === 2 ? 100 : null"
                    :addonBefore="item.shareType === 1 ? '$' : null"
                    :addonAfter="item.shareType === 2 ? '%' : null"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>
        </template>

        <template v-if="step === 1">
          <a-card :bordered="false">
            <a-form-item label="方案標題" name="title">
              <a-input v-model:value="formState.title" />
            </a-form-item>
          </a-card>
        </template>
      </a-form>
    </a-drawer>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import { message, Modal } from "ant-design-vue";
import { PlusOutlined, ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { consultPlanApi } from "@/api";
import BreadcrumbComponent from "@/components/BreadcrumbComponent.vue";
import TableFilter from "@/components/TableFilter.vue";
import DynamicForm from "@/components/DynamicForm.vue";
import {
  tableColumns,
  filterFields,
  getEditFieldConfig,
} from "@/models/consultPlan";
import { useRouter, useRoute } from "vue-router";
import { createPagination } from "@/utils/pagination";
import { watchRouteQuery } from "@/utils/routeQueryWatcherUtil";
import { useCustomConsultTypeStore } from "@/store/customConsultTypeStore";

/******* 頁面狀態與配置 *****************************/
const breadcrumbItems = [{ url: "", name: "診金方案" }];
const columns = tableColumns;
const filterConfig = filterFields;
const createFieldConfig = ref<Record<string, any>>({});
const editFieldConfig = ref<Record<string, any>>({});
const router = useRouter();
const route = useRoute();
const loading = ref(false);
// 分頁配置
const pagination = createPagination();

// 數據
const tableData = ref([]);
const editRecordId = ref<number>(0); // 當前編輯的減免方案ID
const editFormData = reactive<any>({}); // 當前編輯的減免方案數據

/******* 數據獲取與初始化 *****************************/
const fetchData = async (params?: any) => {
  loading.value = true; // 開始加載
  try {
    const {
      data: { list, page, limit, total },
    } = await consultPlanApi.getConsultPlanList(params);
    tableData.value = list || [];
    pagination.updatePagination(page, limit, total);
  } catch (error) {
    console.error("獲取診金方案列表失敗", error);
  } finally {
    loading.value = false; // 結束加載
  }
};

watchRouteQuery(fetchData);

/******* 減免方案操作處理 *****************************/
// 搜索
const handleSearch = (params: any) => {
  router.push({ query: params });
};

// 創建
const customConsultTypeStore = useCustomConsultTypeStore();
const consultTypes = ref([]);
const showCreateDrawer = ref(false);

const formState = reactive({
  title: "",
  items: [],
});
const formRef = ref();
const spinning = ref(false);

// 打開創建抽屜
const handleShowCreateDrawer = async () => {
  showCreateDrawer.value = true;
  spinning.value = true;

  consultTypes.value = await customConsultTypeStore.fetchOptions();
  // console.log("consultTypes", consultTypes.value);

  // 初始化數據
  formState.items = consultTypes.value.map((item) => ({
    name: item.label,
    consultType: item.value,
    shareType: 1,
    shareValue: 0,
  }));
  formState.title = "";
  step.value = 0;
  spinning.value = false;
  // console.log("formState", formState);
};

const step = ref(0);
const handleNextStep = () => {
  step.value++;
};

const handlePrevStep = () => {
  step.value--;
};

// 創建提交

const createFormRef = ref();
const handleCreateSubmit = async () => {
  try {
    await consultPlanApi.createConsultPlan(formState);
    message.success("創建診金方案成功");
    step.value = 0;
    showCreateDrawer.value = false;
    fetchData(route.query);
  } catch (error) {
    console.error("創建減免方案失敗:", error);
  } finally {
    createFormRef.value?.resetLoading();
  }
};

// 修改
const showModalEdit = ref(false);
const handleEdit = (record: any) => {
  if (Object.keys(editFieldConfig.value).length === 0) {
    editFieldConfig.value = getEditFieldConfig();
  }
  editRecordId.value = Number(record.id);
  // 初始化編輯表單數據
  record.validDate = [record.validFrom, record.validTo];
  Object.assign(editFormData, record);
  showModalEdit.value = true;
};

const editFormRef = ref();
const handleEditSubmit = async (data: any) => {
  try {
    await consultPlanApi.updateConsultPlan(editRecordId.value, data);
    message.success("修改診金方案成功");
    showModalEdit.value = false;
    fetchData(route.query);
  } catch (error) {
    console.error("修改診金方案失敗", error);
  } finally {
    editFormRef.value?.resetLoading();
  }
};

// 複製
const handleCopy = async (record: any) => {
  // 獲取當前記錄的ID的items數據
  try {
    showCreateDrawer.value = true;
    spinning.value = true;
    const { data } = await consultPlanApi.getConsultPlanDetail(record.id);
    console.log("data", data);
    consultTypes.value = await customConsultTypeStore.fetchOptions();
    // console.log("consultTypes", consultTypes.value);

    // 初始化數據
    formState.items = data.consultTypes.map((item) => ({
      name: item.name,
      consultType: item.id,
      shareType: item.shareType,
      shareValue: item.shareValue,
    }));
    formState.title = data.title + " _Copy";
    step.value = 0;
    console.log("formState", formState);
  } catch (error) {
    console.error("獲取詳情失敗", error);
  } finally {
    spinning.value = false;
  }
};

// 查看
const handleView = (record: any) => {
  router.push({ name: "ConsultPlanDetail", params: { id: record.id } });
};

// 刪除
const handleDelete = async (record: any) => {
  Modal.confirm({
    title: "確認刪除",
    content: `確定要刪除減免方案 ${record.title} 嗎？`,
    okText: "確定",
    cancelText: "取消",
    onOk: async () => {
      try {
        await consultPlanApi.deleteConsultPlan(record.id);
        message.success("刪除減免方案成功");
        fetchData();
      } catch (error) {
        console.error("刪除減免方案失敗:", error);
      }
    },
  });
};
</script>

<style scoped></style>
